#include "resultwindow.h"
#include <QMainWindow>
#include <QVector>
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QStringList>
#include <QDate>
#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>
#include <QTableWidget>
#include <QHeaderView>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QPushButton>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDate>
#include <QFile>
#include <QMessageBox>
#include <QtMath>
#include <QDialog>
#include <QTableWidget>
#include <QHeaderView>
#include <QFormLayout>
#include <QTextStream>
#include <QVector>

double ResultWindow::getLatestBmi() const {
    return bmi;
}

const char* ResultWindow::getBmiStatus(double bmi) const {
    if (bmi < 18.5) return "偏瘦";
    else if (bmi < 24) return "正常";
    else if (bmi < 28) return "超重";
    else return "肥胖";
}

QVector<double> ResultWindow::loadHistoricalBmi() const {
    QVector<double> historicalBmi;
    QFile file(username + "_records.txt");
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            QStringList parts = line.split(",");
            if (parts.size() == 6) {
                historicalBmi.append(parts[5].toDouble());
            }
        }
        file.close();
    }
    return historicalBmi;
}

QVector<double> ResultWindow::predictFutureBmi(const QVector<double> &historicalBmi) const {
    QVector<double> predictions;
    if (historicalBmi.size() < 2) {
        // 数据不足时使用简单预测
        predictions.append(bmi);
        predictions.append(bmi * 0.99);
        predictions.append(bmi * 0.98);
        predictions.append(bmi * 0.97);
        predictions.append(bmi * 0.96);
        predictions.append(bmi * 0.95);
    } else {
        // 简单线性回归预测
        double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
        int n = historicalBmi.size();
        
        for (int i = 0; i < n; ++i) {
            sumX += i;
            sumY += historicalBmi[i];
            sumXY += i * historicalBmi[i];
            sumX2 += i * i;
        }
        
        double a = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
        double b = (sumY - a * sumX) / n;
        
        for (int i = n; i < n + 6; ++i) {
            predictions.append(a * i + b);
        }
    }
    return predictions;
}

void ResultWindow::showTrendPrediction() {
    QVector<double> historicalBmi = loadHistoricalBmi();
    QVector<double> futureBmi = predictFutureBmi(historicalBmi);
    QDate currentDate = QDate::currentDate();

    // 创建趋势预测对话框
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("📊 BMI趋势分析");
    dialog->resize(700, 600);
    dialog->setStyleSheet("background-color: #f8f9fa;");
    
    QVBoxLayout *mainLayout = new QVBoxLayout(dialog);
    
    // 1. 历史记录表格
    QLabel *historyLabel = new QLabel("📅 历史记录");
    historyLabel->setStyleSheet("font-size: 16pt; color: #495057; font-weight: bold;");
    mainLayout->addWidget(historyLabel);
    
    QTableWidget *historyTable = new QTableWidget();
    historyTable->setColumnCount(4);
    historyTable->setHorizontalHeaderLabels({"序号", "日期", "BMI值", "状态"});
    historyTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    historyTable->setStyleSheet(
        "QTableWidget {"
        "  background-color: white;"
        "  border-radius: 10px;"
        "  padding: 5px;"
        "}"
        "QHeaderView::section {"
        "  background-color: #dee2e6;"
        "  padding: 5px;"
        "  font-weight: bold;"
        "}"
    );
    
    for (int i = 0; i < historicalBmi.size(); ++i) {
        QDate date = currentDate.addMonths(-historicalBmi.size() + i + 1);
        QString status = getBmiStatus(historicalBmi[i]);
        
        historyTable->insertRow(i);
        historyTable->setItem(i, 0, new QTableWidgetItem(QString::number(i + 1)));
        historyTable->setItem(i, 1, new QTableWidgetItem(date.toString("yyyy-MM-dd")));
        historyTable->setItem(i, 2, new QTableWidgetItem(QString::number(historicalBmi[i], 'f', 2)));
        historyTable->setItem(i, 3, new QTableWidgetItem(status));
    }
    mainLayout->addWidget(historyTable);
    
    // 2. 预测结果表格
    QLabel *predictionLabel = new QLabel("🔮 未来6个月预测");
    predictionLabel->setStyleSheet("font-size: 16pt; color: #495057; font-weight: bold; margin-top: 15px;");
    mainLayout->addWidget(predictionLabel);
    
    QTableWidget *predictionTable = new QTableWidget();
    predictionTable->setColumnCount(4);
    predictionTable->setHorizontalHeaderLabels({"序号", "日期", "预测BMI", "预测状态"});
    predictionTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    predictionTable->setStyleSheet(historyTable->styleSheet());
    
    for (int i = 0; i < futureBmi.size(); ++i) {
        QDate date = currentDate.addMonths(i + 1);
        QString status = getBmiStatus(futureBmi[i]);
        
        predictionTable->insertRow(i);
        predictionTable->setItem(i, 0, new QTableWidgetItem(QString::number(i + 1)));
        predictionTable->setItem(i, 1, new QTableWidgetItem(date.toString("yyyy-MM")));
        predictionTable->setItem(i, 2, new QTableWidgetItem(QString::number(futureBmi[i], 'f', 2)));
        predictionTable->setItem(i, 3, new QTableWidgetItem(status));
    }
    mainLayout->addWidget(predictionTable);
    
    // 3. 分析建议
    QLabel *analysisLabel = new QLabel("💡 分析建议");
    analysisLabel->setStyleSheet("font-size: 16pt; color: #495057; font-weight: bold; margin-top: 15px;");
    mainLayout->addWidget(analysisLabel);
    
    QLabel *adviceText = new QLabel();
    adviceText->setStyleSheet(
        "font-size: 14pt; "
        "color: #212529; "
        "background-color: white; "
        "padding: 15px; "
        "border-radius: 10px;"
    );
    adviceText->setWordWrap(true);
    
    if (!historicalBmi.isEmpty()) {
        double lastBmi = historicalBmi.last();
        double predictedBmi = futureBmi.last();
        double change = predictedBmi - lastBmi;
        
        QString advice = "根据分析：\n";
        advice += QString("• 当前BMI: %1 (%2)\n").arg(lastBmi, 0, 'f', 2).arg(getBmiStatus(lastBmi));
        advice += QString("• 6个月后预测BMI: %1 (%2)\n").arg(predictedBmi, 0, 'f', 2).arg(getBmiStatus(predictedBmi));
        
        if (qAbs(change) < 0.5) {
            advice += "• 趋势: 基本保持稳定\n";
            advice += "建议继续保持当前生活习惯，定期监测BMI变化。";
        } else if (change > 0) {
            advice += QString("• 趋势: 预计上升 %1\n").arg(change, 0, 'f', 2);
            advice += "建议适当增加运动量，控制饮食热量摄入，避免体重持续增加。";
        } else {
            advice += QString("• 趋势: 预计下降 %1\n").arg(-change, 0, 'f', 2);
            advice += "继续保持健康习惯，如需进一步减重，建议咨询营养师制定科学计划。";
        }
        
        adviceText->setText(advice);
    } else {
        adviceText->setText("暂无足够历史数据进行分析，请定期记录BMI以获得更准确的趋势预测。");
    }
    mainLayout->addWidget(adviceText);
    
    // 添加关闭按钮
    QPushButton *closeBtn = new QPushButton("关闭");
    closeBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 10px 20px;"
        "  background-color: #6c757d;"
        "  color: white;"
        "  border-radius: 10px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #495057;"
        "}"
    );
    connect(closeBtn, &QPushButton::clicked, dialog, &QDialog::accept);
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeBtn);
    buttonLayout->addStretch();
    mainLayout->addLayout(buttonLayout);
    
    dialog->exec();
}

ResultWindow::ResultWindow(double bmi, const QString &username, QWidget *parent) : 
    QMainWindow(parent), bmi(bmi), username(username)
{
    setWindowTitle("✨ BMI计算结果 ✨");
    resize(600, 500);
    setStyleSheet("background-color: #f8f9fa;");

    QString assessment = getBmiStatus(bmi);

    QLabel *titleLabel = new QLabel("📊 您的BMI结果", this);
    titleLabel->setStyleSheet(
        "font-size: 20pt; "
        "font-weight: bold; "
        "color: #6c757d; "
        "font-family: 'Microsoft YaHei';"
    );

    bmiLabel = new QLabel(QString("🧮 BMI值: %1").arg(bmi, 0, 'f', 2), this);
    bmiLabel->setStyleSheet(
        "font-size: 16pt; "
        "color: #495057;"
    );

    assessmentLabel = new QLabel(QString("🏥 健康评估: %1").arg(assessment), this);
    assessmentLabel->setStyleSheet(
        "font-size: 16pt; "
        "color: #495057;"
    );

    saveBtn = new QPushButton("💾 保存本次记录", this);
    saveBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #adb5bd;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #6c757d;"
        "}"
    );

    adviceBtn = new QPushButton("💡 提供针对性健康建议", this);
    adviceBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #4cc9f0;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #4895ef;"
        "}"
    );

    goalBtn = new QPushButton("🎯 设定理想BMI值", this);
    goalBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #4cc9f0;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #4895ef;"
        "}"
    );

    historyBtn = new QPushButton("📜 查看历史记录", this);
    historyBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #f72585;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #b5179e;"
        "}"
    );

    trendBtn = new QPushButton("🔮 预测BMI趋势", this);
    trendBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #7209b7;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #560bad;"
        "}"
    );

    connect(adviceBtn, &QPushButton::clicked, this, &ResultWindow::requestAdvice);
    connect(goalBtn, &QPushButton::clicked, [this]() {
        emit requestGoalSetting();
    });
    // 历史数据按钮点击处理
    connect(historyBtn, &QPushButton::clicked, this, [this, username]() {
        try {
            QDialog *historyDialog = new QDialog(this);
            historyDialog->setWindowTitle("历史记录 - " + username);
            historyDialog->resize(600, 400);
            
            QTableWidget *table = new QTableWidget(historyDialog);
            table->setColumnCount(4);
            table->setHorizontalHeaderLabels({"日期", "体重(kg)", "身高(cm)", "BMI"});
            table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

            QFile file(username + "_records.txt");
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream stream(&file);
                int row = 0;
                while (!stream.atEnd()) {
                    QString line = stream.readLine();
                    QStringList parts = line.split(",");
                    if (parts.size() >= 6) {
                        table->insertRow(row);
                        table->setItem(row, 0, new QTableWidgetItem(parts[0])); // 日期
                        table->setItem(row, 1, new QTableWidgetItem(parts[2])); // 体重
                        table->setItem(row, 2, new QTableWidgetItem(parts[3])); // 身高
                        table->setItem(row, 3, new QTableWidgetItem(parts[5])); // BMI
                        row++;
                    }
                }
                file.close();
            } else {
                QMessageBox::warning(historyDialog, "警告", "找不到历史记录文件");
            }

            QVBoxLayout *layout = new QVBoxLayout(historyDialog);
            layout->addWidget(table);
            historyDialog->setLayout(layout);
            historyDialog->exec();
            historyDialog->deleteLater();
        } catch (...) {
            QMessageBox::critical(this, "错误", "加载历史数据时发生异常");
        }
    });
    // 趋势预测按钮点击处理
    connect(trendBtn, &QPushButton::clicked, this, [this]() {
        try {
            showTrendPrediction();
        } catch (...) {
            QMessageBox::critical(this, "错误", "生成趋势预测时发生异常");
        }
    });
    connect(saveBtn, &QPushButton::clicked, [this]() {
        QMessageBox::information(this, "保存成功", "本次BMI记录已保存");
    });

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(titleLabel);
    layout->addWidget(bmiLabel);
    layout->addWidget(assessmentLabel);
    layout->addWidget(saveBtn);
    layout->addWidget(adviceBtn);
    layout->addWidget(goalBtn);
    layout->addWidget(historyBtn);
    layout->addWidget(trendBtn);
    layout->addStretch();

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}